using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiApp.Models;
using MauiApp.Services;
using Microsoft.Maui.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
//using static Android.Graphics.Path;

namespace MauiApp.ViewModels
{
    public partial class TypeManageViewModel : ObservableObject
    {
        [ObservableProperty]
        private ObservableCollection<TypesModel> fileTypes = new ObservableCollection<TypesModel>();

        private readonly IApiService _apiService;

        public TypeManageViewModel(IApiService apiService)
        {
            _apiService = apiService;
        }

        // 为XAML编译提供的默认构造函数
        public TypeManageViewModel()
        {
            // 使用应用程序的ServiceProvider获取ApiService实例，确保使用的是同一个单例实例
            _apiService = App.ServiceProvider.GetRequiredService<IApiService>();
        }

        [RelayCommand]
        public async Task InitializeAsync()
        {
            try
            {
                FileTypes.Clear();
                // 获取当前登录的用户名
                string username = _apiService.GetCurrentUsername();
                
                if (string.IsNullOrEmpty(username))
                {
                    // 获取所有文件类型（备用方案）
                    var types = await _apiService.GetFileTypesAsync();
                    if (types != null)
                    {
                        foreach (var type in types)
                        {
                            FileTypes.Add(type);
                        }
                    }
                }
                else
                {
                    // 根据当前用户ID获取文件类型
                    var types = await _apiService.GetFileTypesByUserAsync(username);
                    if (types != null)
                    {
                        foreach (var type in types)
                        {
                            FileTypes.Add(type);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var mainPage = Application.Current.Windows.FirstOrDefault()?.Page;
                if (mainPage != null)
                {
                    await mainPage.DisplayAlert("错误", $"初始化失败: {ex.Message}", "确定");
                }
            }
        }
        [RelayCommand]
        public async Task RefreshFileTypesAsync()
        {
            try
            {
                FileTypes.Clear();
                // 获取当前登录的用户名
                string username = _apiService.GetCurrentUsername();
                
                if (string.IsNullOrEmpty(username))
                {
                    // 获取所有文件类型（备用方案）
                    var types = await _apiService.GetFileTypesAsync();
                    if (types != null)
                    {
                        foreach (var type in types)
                        {
                            FileTypes.Add(type);
                        }
                    }
                }
                else
                {
                    // 根据当前用户ID获取文件类型
                    var types = await _apiService.GetFileTypesByUserAsync(username);
                    if (types != null)
                    {
                        foreach (var type in types)
                        {
                            FileTypes.Add(type);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var mainPage = Application.Current.Windows.FirstOrDefault()?.Page;
                if (mainPage != null)
                {
                    await mainPage.DisplayAlert("错误", $"刷新类型列表时发生错误: {ex.Message}", "确定");
                }
            }
        }

        // 添加一个用于添加文件类型的命令，接受页面参数以访问输入控件
        [RelayCommand]
        public async Task AddFileType(object parameter)
        {
            if (parameter is not ContentPage page)
            {
                return;
            }

            var fileTypeInput = page.FindByName<Entry>("FileTypeInput");
            var memoryStrengthInput = page.FindByName<Entry>("MemoryStrengthInput");

            if (fileTypeInput == null || memoryStrengthInput == null)
            {
                return;
            }

            // 获取当前页面引用用于显示对话框
            var mainPage = Application.Current?.Windows.FirstOrDefault()?.Page;
            if (mainPage == null)
                return;

            // 验证输入
            if (string.IsNullOrWhiteSpace(fileTypeInput.Text))
            {
                await mainPage.DisplayAlert("错误", "请输入文件类型名称", "确定");
                return;
            }

            if (string.IsNullOrWhiteSpace(memoryStrengthInput.Text))
            {
                await mainPage.DisplayAlert("错误", "请输入记忆强度系数S", "确定");
                return;
            }

            if (!double.TryParse(memoryStrengthInput.Text, out double memoryStrength))
            {
                await mainPage.DisplayAlert("错误", "请输入有效的记忆强度系数", "确定");
                return;
            }

            // 创建新的文件类型，设置用户ID
            var newFileType = new TypesModel
            {
                FileTypeName = fileTypeInput.Text,
                MemoryStrength = memoryStrength,
                UserId = _apiService.GetCurrentUsername() // 使用当前登录用户名
            };

            try
            {
                var success = await _apiService.AddFileTypeAsync(newFileType);
                
                if (success)
                {
                    // 清空输入框
                    fileTypeInput.Text = string.Empty;
                    memoryStrengthInput.Text = string.Empty;
                    
                    await RefreshFileTypesAsync();
                    await mainPage.DisplayAlert("成功", "文件类型添加成功", "确定");
                }
                else
                {
                    await mainPage.DisplayAlert("失败", "文件类型添加失败", "确定");
                }
            }
            catch (Exception ex)
            {
                await mainPage.DisplayAlert("错误", $"添加文件类型时发生错误: {ex.Message}", "确定");
            }
        }
        
        // 添加一个用于编辑文件类型的命令
        [RelayCommand]
        public async Task EditFileType(int fileTypeId)
        {
            try
            {
                // 获取当前页面引用
                var mainPage = Application.Current?.Windows.FirstOrDefault()?.Page;
                if (mainPage == null)
                    return;

                // 找到要编辑的文件类型
                var fileType = FileTypes.FirstOrDefault(t => t.FileTypeID == fileTypeId);
                if (fileType == null)
                {
                    await mainPage.DisplayAlert("错误", "找不到指定的文件类型", "确定");
                    return;
                }

                // 创建临时变量存储原始值
                string originalName = fileType.FileTypeName;
                double originalStrength = fileType.MemoryStrength;

                // 创建自定义的编辑弹窗内容
                var stackLayout = new StackLayout
                {
                    Padding = 20,
                    Spacing = 15,
                    Children = {
                        new Label { Text = "文件类型名称", FontSize = 16 },
                        new Entry { Text = originalName, StyleId = "FileTypeInput" },
                        new Label { Text = "记忆强度系数S", FontSize = 16 },
                        new Entry { Text = originalStrength.ToString(), Keyboard = Keyboard.Numeric, StyleId = "MemoryStrengthInput" }
                    }
                };

                // 使用AlertDialog的替代方案，通过自定义的模态弹窗实现
                var editPage = new ContentPage
                {
                    Title = "编辑文件类型",
                    Content = stackLayout
                };

                // 获取输入控件
                var editFileTypeInput = (Entry)stackLayout.Children[1];
                var editMemoryStrengthInput = (Entry)stackLayout.Children[3];

                // 添加底部按钮
                var buttonLayout = new HorizontalStackLayout
                {
                    Spacing = 10,
                    HorizontalOptions = LayoutOptions.End,
                    Padding = new Thickness(0, 10, 10, 10)
                };

                var cancelButton = new Button
                {
                    Text = "取消",
                    WidthRequest = 100,
                    Command = new Command(async () =>
                    {
                        var currentWindow = Application.Current?.Windows.FirstOrDefault();
                        if (currentWindow != null && currentWindow.Navigation != null)
                        {
                            await currentWindow.Navigation.PopModalAsync();
                        }
                    })
                };

                var saveButton = new Button
                {
                    Text = "保存",
                    WidthRequest = 100,
                    BackgroundColor = Colors.Green,
                    TextColor = Colors.White,
                    Command = new Command(async () =>
                    {
                        // 验证输入
                        if (string.IsNullOrWhiteSpace(editFileTypeInput.Text))
                        {
                            await mainPage.DisplayAlert("错误", "请输入文件类型名称", "确定");
                            return;
                        }

                        if (string.IsNullOrWhiteSpace(editMemoryStrengthInput.Text) ||
                            !double.TryParse(editMemoryStrengthInput.Text, out double memoryStrength))
                        {
                            await mainPage.DisplayAlert("错误", "请输入有效的记忆强度系数", "确定");
                            return;
                        }

                        // 更新文件类型，保留原始的UserId
                        var updatedFileType = new TypesModel
                        {
                            FileTypeID = fileTypeId,
                            FileTypeName = editFileTypeInput.Text,
                            MemoryStrength = memoryStrength,
                            UserId = fileType.UserId // 保留原始用户ID
                        };

                        var success = await _apiService.UpdateFileTypeAsync(updatedFileType);
                        
                        if (success)
                        {
                            await RefreshFileTypesAsync();
                            await mainPage.DisplayAlert("成功", "文件类型更新成功", "确定");
                            
                            var currentWindow = Application.Current?.Windows.FirstOrDefault();
                            if (currentWindow != null && currentWindow.Navigation != null)
                            {
                                await currentWindow.Navigation.PopModalAsync();
                            }
                        }
                        else
                        {
                            await mainPage.DisplayAlert("错误", "文件类型更新失败", "确定");
                        }
                    })
                };

                buttonLayout.Children.Add(cancelButton);
                buttonLayout.Children.Add(saveButton);
                stackLayout.Children.Add(buttonLayout);

                // 显示编辑页面作为模态对话框
                var currentWindow = Application.Current?.Windows.FirstOrDefault();
                if (currentWindow != null && currentWindow.Navigation != null)
                {
                    await currentWindow.Navigation.PushModalAsync(editPage);
                }
            }
            catch (Exception ex)
            {
                var mainPage = Application.Current?.Windows.FirstOrDefault()?.Page;
                if (mainPage != null)
                {
                    await mainPage.DisplayAlert("错误", $"编辑文件类型时发生错误: {ex.Message}", "确定");
                }
            }
        }

        // 添加一个用于删除文件类型的命令
        [RelayCommand]
        public async Task DeleteFileType(int fileTypeId)
        {
            try
            {
                // 获取当前页面引用
                var mainPage = Application.Current?.Windows.FirstOrDefault()?.Page;
                if (mainPage == null)
                    return;
                
                bool confirmDelete = await mainPage.DisplayAlert(
                    "确认删除",
                    "确定要删除这个文件类型吗？",
                    "确定",
                    "取消");
                
                if (confirmDelete)
                {
                    var success = await _apiService.DeleteFileTypeAsync(fileTypeId);
                    
                    if (success)
                    {
                        await RefreshFileTypesAsync();
                        await mainPage.DisplayAlert("成功", "文件类型删除成功", "确定");
                    }
                    else
                    {
                        await mainPage.DisplayAlert("错误", "文件类型删除失败", "确定");
                    }
                }
            }
            catch (Exception ex)
            {
                var mainPage = Application.Current?.Windows.FirstOrDefault()?.Page;
                if (mainPage != null)
                {
                    await mainPage.DisplayAlert("错误", $"删除文件类型时发生错误: {ex.Message}", "确定");
                }
            }
        }
    }
}
